######################################
#### table_2.R: Generates Table 2 ####
######################################

q6 <- read.csv(here("Data","midterm_fraud_open_ends6.csv"), stringsAsFactors=FALSE)
q6<-q6[,c(1,3)]
df <-merge(dta_midterm,q6)

df$w9_2022_1_elections6_code[df$w9_2022_1_elections6_code=="99"] <-7
results <- pollster::moe_crosstab(df, y=w9_2022_1_elections6_code, x=pid, weight=weight) %>%
  mutate(upper = pct+moe) %>%
  mutate(lower = pct-moe) %>%
  mutate(wn = round(n*(pct/100),0))

results$w9_2022_1_elections6_code <- recode(results$w9_2022_1_elections6_code, 
                                            '1' = "Logical deduction",
                                            '21' = "Takes too long to count votes",
                                            '22' = "Ballot harvesting/Mail",
                                            '23' = "Voting machine problems",
                                            '24' = "Voting procedure conspiracy",
                                            '3' = "Democrats winning",
                                            '4' = "The Media",
                                            '5' = "Convictions",
                                            '6' = "Gerrymandering",
                                            '7'	= "No evidence offered")

results_full = pollster::moe_topline(df, w9_2022_1_elections6_code, weight = weight) |>
  mutate(pid = "Full",
         wn = round(Frequency*(Percent/100),0),
         w9_2022_1_elections6_code = case_match(
           Response,
           '1'  ~ "Logical deduction",
           '21' ~ "Takes too long to count votes",
           '22' ~ "Ballot harvesting/Mail",
           '23' ~ "Voting machine problems",
           '24' ~ "Voting procedure conspiracy",
           '3'  ~ "Democrats winning",
           '4'  ~ "The Media",
           '5'  ~ "Convictions",
           '6'  ~ "Gerrymandering",
           '7'	~ "No evidence offered"
         )) |> 
  rename(pct = Percent)

results |> 
  bind_rows(results_full) |> 
  select(pid, w9_2022_1_elections6_code, pct, wn) |> 
  filter(w9_2022_1_elections6_code %in% c("Ballot harvesting/Mail","Takes too long to count votes",
                                          "Voting machine problems","Voting procedure conspiracy")) |> 
  print(n = 27)